package org.xxpay.pay.channel.xinanpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import freemarker.template.utility.StringUtil;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;
@Service
public class XinanpayPaymentService extends BasePayment {
    private final static String logPrefix = "【信安支付】";
    @Override
    public String getChannelName() {
        return XinanpayConfig.CHANNEL_NAME;
    }
    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case XinanpayConfig.CHANMEL_NAME_QUICK:
                retObj = doOrderReq(payOrder, "");
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
        XinanpayConfig config = new XinanpayConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("sp_id", config.getAppId());
        params.put("mch_id", config.getMchId());
        params.put("out_trade_no",payOrder.getPayOrderId());
        params.put("nonce_str", payOrder.getPayOrderId());
        params.put("sign", getSign(params, config.getPrivateKey()));
        _log.info("{}订单查询请求数据:{}", getChannelName(), JSON.toJSONString(params));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+XinanpayConfig.REQ_PAY_QUERY_URL_FIXX, params, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("status"), "SUCCESS")) {
            String payStatus = origin.getString("trade_state");
            if(StringUtils.equals(payStatus,"SUCCESS")){
                //支付成功
                retObj.put("status",2);
            }else{
                //支付中
                retObj.put("status",1);
            }
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("out_trade_no"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("message"));
        return retObj;
    }
    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder,String payType){
        XinanpayConfig config = new XinanpayConfig(getPayParam(payOrder));
        Map<String,Object> params = Maps.newHashMap();
        //设置参数
        setParams(payOrder,config,params);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));
        //将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+XinanpayConfig.REQ_PAY_URL_FIXX, params, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals("SUCCESS",origin.getString("status"))){
            return buildPayResultOfForm(retObj, payOrder,"<script type=\"text/javascript\">\n" +
                    "　　window.location.href=\""+ origin.getString("ret_url")+"\";\n" +
                    "　　</script>" );
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.toJSONString());
        return retObj;
    }
    //设置下单请求参数
    private void setParams(PayOrder payOrder, XinanpayConfig config, Map<String,Object> params){

        params.put("sp_id", config.getAppId());
        params.put("mch_id", config.getMchId());
        params.put("out_trade_no", payOrder.getPayOrderId());
        params.put("total_fee", payOrder.getAmount());//单位 分
        params.put("body", payOrder.getPayOrderId());
        params.put("notify_url", payConfig.getNotifyUrl(getChannelName()));
        //params.put("accNo", "");
        if(!StringUtils.equals(null,payOrder.getReturnUrl())&&payOrder.getReturnUrl().length()>0){
            params.put("callback_url", payOrder.getReturnUrl());
        }
        params.put("nonce_str", payOrder.getPayOrderId());
        params.put("sign", getSign(params,config.getPrivateKey()));

    }
    //获取sign
    private String getSign(Map<String,Object> params,String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+"&key="+key);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8).toUpperCase();
        return sign;
    }
}
